import 'package:app/components/index.dart';
import 'package:flutter/material.dart';
import 'package:qrscan/qrscan.dart' as scanner;

import '../../api/call-material/index.dart';
import '../../util/StringUtils.dart';

///生产叫料
class CallMaterial extends StatefulWidget {
  const CallMaterial({super.key});
  @override
  State<CallMaterial> createState() => CallMaterialState();
}

class CallMaterialState extends State<CallMaterial> {
  final GlobalKey<FormState>? _formKey = GlobalKey<FormState>();
  final FocusNode _firstFocusNode = FocusNode();


  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      FocusScope.of(context).requestFocus(_firstFocusNode);
    });
  }

  //任务号
  String _code = "";
  // 工序部门
  String _processDep = "";
  // 工序班组
  String _processClass = "";
  //设置开始配送按钮是否可用
  bool isButtonEnabled = false;

  ///设置表单值
  List<dynamic> _data = [];

  @override
  void dispose() {
    super.dispose();
    _firstFocusNode.dispose();
  }

  void scan() async{
    String? qrCode = await scanner.scan();
    setState(() => _code = qrCode.toString());
  }

  void setValue(String key, String value, bool bool) {
    switch (key) {
      case '_code':
        _code = value;
      case 'isButtonEnabled':
        isButtonEnabled = bool;
        break;
      default:
        throw Exception("key error");
    }
  }

  void hideKeyBorder() {
    FocusScopeNode currentFocus = FocusScope.of(context);
    if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
      FocusManager.instance.primaryFocus?.unfocus();
    }
  }

  ///查找拣配单列表
  void picks() {
    CallMaterialApi.of(context).picks(_code).then((res) {
      if (StringUtils.isNotNull(res) && StringUtils.isNotNull(res.data)) {
        if (res.data['data'].length == 0) {
          Confirm.of(context).showText('当前没有待配送的物料。', () =>
          {
            Navigator.pushNamed(context, '/home')
          }, '关闭', '返回');
        } else {
          handlerResult(res.data);
        }
      }
    });
  }

  /// 处理返回结果
  void handlerResult(res) {
    setState(() {
      _processDep = res['data']?[0]['deptName'];
      _processClass = res['data']?[0]['wcName'];
      _data = res['data']??null;
    });
  }


  ///详情
  void detail(int index) {
    Navigator.pushNamed(context, "/product-material-detail", arguments: {
      'processDep': _processDep,
      'processClass': _processClass,
      'code': _code,
      'status': _data[index]['lackMaterialStatus'],
      'pickId': _data[index]['pickId'],
      'container': _data[index]['container']
    });
  }

  /// 提交配送
  void submit() {
    Forms.validate(_formKey!).then((valid){
      if(valid && StringUtils.isNotNull(_data)){
        if(_data?[0]['lackMaterialStatus'] == "1"){
          createDelivery();
        }else{
          Confirm.of(context).show('物料不全，请确认是否配送？', ()=>{createDelivery()});
        }
      }
    });
  }

  /// 创建配送单
  void createDelivery(){
      CallMaterialApi.of(context).createDelivery({'endStation': _code, 'pickId': _data[0]['pickId']}).then((res){
        if(StringUtils.isNotNull(res) && StringUtils.isNotNull(res.data)){
          final size = res.data['data']['size']??0;
          Success.of(context).show('呼叫成功，还有${size}个托盘未呼叫');
          Navigator.pop(context);
          Navigator.pushNamed(context, "/product-material-request");
        }
      });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBars(context: context, title: '生产叫料'),
      body: GestureDetector(
        onTap: hideKeyBorder,
        child: Column(
          children: [
            Group(
              // title: '班组信息',
              context: context,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Forms(
                    formKey: _formKey,
                    formItem: [
                      FormItem(
                        type: 'input',
                        labelWidth: 90,
                        focusNode: _firstFocusNode,
                        labelText: '站  点  码:',
                        placeholder: '请扫描站点码',
                        filedName: 'code',
                        icon: const Icon(Icons.qr_code_scanner_rounded),
                        iconOnTap: scan,
                        value: _code,
                        onEntry: (value)=>{picks()},
                        onChange: (value) =>
                            setValue('_code', value, isButtonEnabled = true),
                        rules: const {
                          'code': [
                            {'required': true, 'message': '站点码不能为空'}
                          ]
                        },
                      ),
                      // FormItem(
                      //     type: 'input',
                      //     labelWidth: 90,
                      //     labelText: '工序部门:',
                      //     value: _processDep,
                      //     icon: const Icon(Icons.account_box),
                      //     enabled: false
                      // ),
                      FormItem(
                          type: 'input',
                          labelWidth: 90,
                          labelText: '工序班组:',
                          filedName: 'processClass',
                          value: _processClass,
                          icon: const Icon(Icons.dashboard),
                          enabled: false
                      ),
                    ],
                  ),
                ],
              ),
            ),
            Expanded(
              child: ListContainer(
                // title: '拣配信息',
                length: _data.length,
                actions: [
                  SlidActions(
                    onPressed: detail,
                    label: '查看详细',
                    icon: Icons.library_books_outlined,
                    backgroundColor: Colors.green
                  )
                ],
                children: (index) {
                  return [
                    Horizontal(
                      items: [
                        HorizontalItem(
                          label: "拣配单号：",
                          value: _data[index]['code'],
                        ),
                        HorizontalItem(
                          label: "优先级：",
                          fontColor: const Color.fromARGB(255, 255, 255, 255),
                          value: _data[index]['priority'].toString(),
                          valueBackground: const Color.fromARGB(
                              255, 69, 228, 194),
                        )
                      ],
                    ),
                    Horizontal(
                      items: [
                        HorizontalItem(
                          label: "托  盘  号：",
                          value: _data[index]['container'],
                        ),
                        HorizontalItem(
                          label: "状态：",
                          fontColor: const Color.fromARGB(255, 255, 255, 255),
                          value: _data[index]['lackMaterialStatus'] == '0'
                              ? '未齐套'
                              : '齐套',
                          valueBackground: _data[index]['lackMaterialStatus'] ==
                              '0' ? const Color.fromARGB(
                              255, 239, 110, 110) : const Color.fromARGB(255,
                              110, 182, 239),
                        )
                      ],
                    ),
                    // ListButton(
                    //     buttons: [
                    //       SizedBox(
                    //         width: 120,
                    //         child: Button(
                    //           onPressed: () => {detail(index)},
                    //           label: ' 清单查看',
                    //           icon: Icons.library_books_outlined,
                    //           fontSize: 15,
                    //           iconColor: Colors.white,
                    //           backgroundColor: Colors.green,
                    //         ),
                    //       )
                    //     ]
                    // )
                  ];
                },
              ),
            ),
            SizedBox(
              width: MediaQuery
                  .of(context)
                  .size
                  .width,
              child: Padding(
                padding: const EdgeInsets.only(top: 10, left: 20, right: 20),
                child: Button(
                  onPressed: isButtonEnabled ? submit : null,
                  backgroundColor: isButtonEnabled
                      ? const Color.fromARGB(255, 60, 98, 60)
                      : Colors.grey,
                  label: '开始配送',
                  height: 60,
                  fontSize: 18,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}